package com.dchh.android.suverynew.module.http.impl;

import android.os.Handler;

import com.alibaba.fastjson.JSONObject;
import com.dchh.android.suverynew.common.ICommonModelListener;
import com.dchh.android.suverynew.http.CommonAction0;
import com.dchh.android.suverynew.http.CommonSubscriber;
import com.dchh.android.suverynew.http.RetrofitManager;
import com.dchh.android.suverynew.http.services.ICommonService;
import com.dchh.android.suverynew.module.http.ILoginModule;
import com.dhcc.android.base.utils.Constants;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by eric on 2016/8/6.
 */
public class LoginModule extends CommonModule implements ILoginModule {

    private ILoginModuleListener mLoginModuleListener;
    private ICommonService mCommonService;

    public LoginModule(ILoginModuleListener loginModuleListener) {
        super(loginModuleListener);
        mLoginModuleListener = loginModuleListener;
        this.mCommonService = RetrofitManager.newInstance().getRetrofit().create(ICommonService.class);
    }

    @Override
    public void updateVersion(boolean isLastException) {
        if (Constants.info != null && Constants.needUpdate) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mLoginModuleListener.onShouldUpdate();
                }
            }, 200);
        } else {
            if (isLastException) {
                mLoginModuleListener.onLastIsException();
            }
        }
    }


    @Override
    public void login() {
        this.mCommonService.login().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new CommonAction0(this.mLoginModuleListener))
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonSubscriber<JSONObject>(this.mLoginModuleListener) {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        mLoginModuleListener.onLoginSUccess(jsonObject);
                    }
                });
    }

    public interface ILoginModuleListener extends ICommonModelListener {
        void onShouldUpdate();

        void onLastIsException();

        void onLoginSUccess(JSONObject jsonObject);

    }
}
